<!--
 * @Descripttion:  
 * @version:  
 * @Author: chenxf
 * @Date: 2023-03-02 11:10:08
-->
<template>
  <a-modal
    :title="title"
    :width="modalWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :bodyStyle="bodyStyle"
    style="top: 0px;"
    destroyOnClose
    :footer="null"
    cancelText="关闭"
    v-if="visible"
  >
    <!-- <a-spin :spinning="confirmLoading"> -->
    <div class="content-wrapper">
      <div class="content-left">
        <div class="process-name">
          <span>【{{ info.processName }}】版本列表</span>
        </div>
        <template v-if="!versionLoading">
          <div
            class="version-list"
            v-for="item in versionLists"
            :class="{ select: selectVersion.id == item.id }"
            @click="changeVersion(item)"
          >
            <!-- <span>{{ item.name }} </span> -->
            <a-tag color="blue"> 版本({{ item.version }}) </a-tag>
            <a-tag color="green" @click.stop="handleCopyVersion(item)" title="拷贝" style="cursor: pointer;">
              <a-icon type="copy" />
            </a-tag>
          </div>
        </template>
        <a-spin v-else class="spin-wrapper">
          <a-icon slot="indicator" type="loading" style="font-size: 30px" spin />
        </a-spin>
      </div>
      <div class="content-main">
        <template v-if="!nodeLoading">
          <div class="deployment-node-wrapper">
            <div class="deployment-node-title">流程节点:</div>
            <div
              v-for="item in deploymentNodeLists"
              class="deployment-node"
              :class="{ select: selectDeploymentNode.id == item.id }"
              @click="changeDeploymentNode(item)"
            >
              {{ item.processNodeName }}
            </div>
          </div>
          <template v-if="!formLoading">
            <div class="assignee-configs-form">
              <div class="table-tool">
                <a-button @click="handleCopyNode" v-if="isEdit">拷贝节点</a-button>
                <a-button @click="addRow">添加行</a-button>
                <a-button @click="deleteNode" type="danger" v-if="isEdit">删除节点流程条件配置</a-button>
              </div>
              <div class="assignee-configs-form-inner" v-if="form.processConditionConfig.length">
                <a-form-model
                  ref="ruleForm"
                  :model="form"
                  :rules="rules"
                  :label-col="labelCol"
                  :wrapper-col="wrapperCol"
                  :layout="'inline'"
                >
                  <a-row class="table-header">
                    <a-col span="4">字段</a-col>
                    <a-col span="4">名称</a-col>
                    <a-col span="2">是否必填</a-col>
                    <a-col span="4">组件名称</a-col>
                    <a-col span="8">组件参数</a-col>
                    <a-col span="2">操作</a-col>
                  </a-row>
                  <template v-for="(config, index) in form.processConditionConfig">
                    <a-row class="table-tr">
                      <a-col span="4">
                        <a-form-model-item
                          label=""
                          :prop="'processConditionConfig.' + index + '.column'"
                          :rules="{
                            required: true,
                            message: '字段不能为空',
                            trigger: 'blur'
                          }"
                        >
                          <a-input v-model="config.column" style="width:120px" />
                        </a-form-model-item>
                      </a-col>
                      <a-col span="4">
                        <a-form-model-item
                          label=""
                          :prop="'processConditionConfig.' + index + '.name'"
                          :rules="{
                            required: true,
                            message: '名称不能为空',
                            trigger: 'blur'
                          }"
                        >
                          <a-input v-model="config.name" style="width:120px" />
                        </a-form-model-item>
                      </a-col>
                      <a-col span="2">
                        <a-form-model-item label="" :prop="'processConditionConfig.' + index + '.require'">
                          <a-switch
                            checked-children="是"
                            un-checked-children="否"
                            default-checked
                            v-model="config.require"
                          />
                        </a-form-model-item>
                      </a-col>
                      <a-col span="4">
                        <a-form-model-item
                          label=""
                          :prop="'processConditionConfig.' + index + '.tagName'"
                          :rules="{
                            message: '名称不能为空',
                            trigger: 'blur'
                          }"
                        >
                          <a-input v-model="config.tagName" style="width:120px" />
                        </a-form-model-item>
                      </a-col>
                      <a-col span="8">
                        <a-form-model-item
                          label=""
                          :prop="'processConditionConfig.' + index + '.tagParam'"
                          :rules="{
                            message: '名称不能为空',
                            trigger: 'blur'
                          }"
                        >
                          <a-input v-model="config.tagParam" style="width:250px" />
                        </a-form-model-item>
                      </a-col>
                      <a-col span="2">
                        <div class="form-delete" @click="removeConfig(config)">
                          <a-icon type="minus-circle-o"></a-icon></div
                      ></a-col>
                    </a-row>
                  </template>
                </a-form-model>
              </div>
              <div class="assignee-configs-form-tip" v-if="form.processConditionConfig.length == 0">
                <a-empty description="请添加数据" />
              </div>
            </div>
            <div class="form-footer" v-if="form.processConditionConfig.length">
              <a-button type="primary" @click="submitEvent" :loading="isLoading">保存</a-button>
            </div>
          </template>
          <a-spin v-else class="spin-wrapper">
            <a-icon slot="indicator" type="loading" style="font-size: 30px" spin />
          </a-spin>
        </template>
        <a-spin v-else class="spin-wrapper">
          <a-icon slot="indicator" type="loading" style="font-size: 40px" spin />
        </a-spin>
      </div>
    </div>
    <a-modal v-model="visibleVersion" :title="'版本(' + copyVersion.version + ')拷贝至'" on-ok="handleOk">
      <template slot="footer">
        <a-button key="back" @click="cancelVisible">
          取消
        </a-button>
        <a-button key="submit" type="primary" @click="saveCopyVersion">
          拷贝
        </a-button>
      </template>
      <a-radio-group v-model="copyVersionId">
        <a-radio
          :value="item.deploymentId"
          v-for="item in versionLists"
          :disabled="copyVersion.deploymentId == item.deploymentId"
          :key="item.deploymentId"
        >
          版本 {{ item.version }}
        </a-radio>
      </a-radio-group>
      <br />
      <a-checkbox v-model="duplicateAllAssignee">
        是否拷贝到所有流程条件配置
      </a-checkbox>
    </a-modal>
    <a-modal v-model="visibleNode" :title="'节点(' + copyNode.processNodeName + ')拷贝至'" on-ok="handleOk">
      <template slot="footer">
        <a-button key="back" @click="cancelVisibleNode">
          取消
        </a-button>
        <a-button key="submit" type="primary" @click="saveCopyNode">
          拷贝
        </a-button>
      </template>
      <a-checkbox-group v-model="copyNodeId">
        <a-checkbox
          :value="item.processNodeCode"
          v-for="item in deploymentNodeLists"
          :disabled="copyNode.processNodeCode == item.processNodeCode"
          :key="item.processNodeCode"
        >
          节点- {{ item.processNodeName }}
        </a-checkbox>
      </a-checkbox-group>
      <br />
      <a-checkbox v-model="duplicateAllAssigneeNode">
        是否拷贝到所有流程条件配置
      </a-checkbox>
    </a-modal>
    <!-- </a-spin> -->
  </a-modal>
</template>

<script>
import { httpAction, getAction, postAction, putAction, deleteAction } from '@/api/manage'
export default {
  name: 'ProcessConditionsModal2',
  components: {},
  props: {
    visible: Boolean,
    info: Object
  },
  data() {
    return {
      title: '流程条件',
      modalWidth: 1200,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      bodyStyle: {
        padding: '0',
        height: window.innerHeight - 80 + 'px'
      },
      confirmLoading: false,
      processKey: '',
      nodeList: '/act/process/extActProcessNodeDeployment/list',
      historyList: '/act/process/extActProcess/processDeploymentList',
      versionLists: [],
      selectVersion: {},
      extActProcessNode: '/act/process/extActProcessNode/list',
      deploymentNodeLists: [],
      selectDeploymentNode: {},
      form: {
        actEventType: 'TASK_CREATED',
        assigneeConditionConfig: '',
        assigneeTypeConfig: '',
        notifyAssignee: '',
        processConditionConfig: []
      },
      isEdit: false,
      rules: {},
      visibleVersion: false,
      copyVersionId: undefined,
      copyVersion: {},
      nodeLoading: false,
      versionLoading: false,
      isLoading: false,
      formLoading: false,
      visibleNode: false,
      copyNode: {},
      copyNodeId: [],
      duplicateAllAssigneeNode: false,
      duplicateAllAssignee: true
    }
  },
  mounted() {
    this.getHistory()
  },
  methods: {
    close() {
      this.$emit('close')
      this.$emit('update:visible', false)
    },
    handleOk() {
      const that = this
      that.$emit('ok')
    },
    handleCancel() {
      this.close()
    },
    getHistory() {
      this.versionLoading = true
      getAction(this.historyList, { processKey: this.info.processKey }).then(res => {
        if (res.success) {
          this.versionLists = res.result.rows
          this.selectVersion = this.versionLists[0]
          if (this.versionLists.length) {
            this.deploymentId = this.versionLists[0].deploymentId
            this.getNodeHistory()
          } else {
            this.nodeLoading = false
          }
        } else {
          this.$message.warning(res.message)
          this.versionLists = []
          this.nodeLoading = false
        }
        this.versionLoading = false
      })
    },
    getNodeHistory() {
      this.nodeLoading = true
      getAction(this.nodeList, { deploymentId: this.selectVersion.deploymentId }).then(res => {
        if (res.success) {
          this.deploymentNodeLists = res.result.rows
          this.selectDeploymentNode = this.deploymentNodeLists[0]
          this.getConfig()
        } else {
          this.$message.warning(res.message)
          this.deploymentNodeLists = []
        }
        this.nodeLoading = false
      })
    },
    getConfig() {
      const postData = {
        actProcessNodeCode: this.selectDeploymentNode.processNodeCode,
        deploymentId: this.selectVersion.deploymentId,
        actProcessId: this.info.id,
        pageSize: 500
      }
      this.formLoading = true
      getAction('/act/processConditions', postData).then(res => {
        if (res.result.rows.length) {
          let form = res.result.rows[0]
          this.form = {
            ...form,
            processConditionConfig: form.processConditionConfig.map(i => {
              let tagName = undefined
              let tagParam = undefined
              try {
                let json = i.tag ? i.tag : {}
                tagName = json.tagName ? json.tagName : undefined
                tagParam = json.tagParam != '' ? JSON.stringify(json.tagParam) : undefined
              } catch (e) {
                this.$message.error('读取配置出错')
              }
              return { ...i, tagName, tagParam }
            })
          }
          this.isEdit = true
        } else {
          this.form = {
            actEventType: 'TASK_CREATED',
            assigneeConditionConfig: '',
            assigneeTypeConfig: '',
            notifyAssignee: '',
            processConditionConfig: []
          }
          this.isEdit = false
        }
        this.formLoading = false
      })
    },
    changeVersion(row) {
      this.selectVersion = row
      this.getNodeHistory()
    },
    changeDeploymentNode(row) {
      this.selectDeploymentNode = row
      this.getConfig()
    },
    addRow() {
      this.form.processConditionConfig.push({
        column: undefined,
        name: undefined,
        require: true,
        tagName: undefined,
        tagParam: undefined
      })
    },
    //提交
    submitEvent() {
      this.$refs.ruleForm.validate((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
        } else {
          this.saveNodeConfig()
        }
      })
    },
    saveNodeConfig() {
      this.isLoading = true
      if (!this.isEdit) {
        const postData = {
          actEventType: 'TASK_CREATED',
          actProcessId: this.info.id,
          actProcessNodeCode: this.selectDeploymentNode.processNodeCode,
          deploymentId: this.selectVersion.deploymentId
        }
        var isError = false
        postData.processConditionConfig = this.form.processConditionConfig.map(i => {
          let tag = undefined
          let config = {}
          try {
            config = i
            tag = {
              tagName: config.tagName,
              tagParam: config.tagParam ? JSON.parse(config.tagParam) : undefined
            }
            delete config.tagName
            delete config.tagParam
          } catch (e) {
            isError = true
            this.$message.error('组件参数有误')
          }
          return { ...config, tag }
        })
        console.log(postData)
        if (isError) {
          return
        }
        postAction('/act/processConditions', postData)
          .then(res => {
            if (res.success) {
              this.$message.success('保存成功')
              this.getConfig()
            } else {
              this.$message.error(res.message)
            }
            this.isLoading = false
          })
          .catch(() => {
            this.isLoading = false
          })
      } else {
        const postData = {
          actEventType: 'TASK_CREATED',
          actProcessId: this.info.id,
          actProcessNodeCode: this.selectDeploymentNode.processNodeCode,
          deploymentId: this.selectVersion.deploymentId,
          id: this.form.id
        }
        var isError = false
        postData.processConditionConfig = this.form.processConditionConfig.map(i => {
          let tag = undefined
          let config = {}
          try {
            config = i
            tag = {
              tagName: config.tagName,
              tagParam: config.tagParam ? JSON.parse(config.tagParam) : undefined
            }
            delete config.tagName
            delete config.tagParam
          } catch (e) {
            isError = true
            this.$message.error('组件参数有误')
          }
          return { ...config, tag }
        })
        console.log(this.form, postData)
        if (isError) {
          return
        }
        putAction('/act/processConditions', postData).then(res => {
          if (res.success) {
            this.$message.success('保存成功')
            this.getConfig()
          } else {
            this.$message.error(res.message)
          }
          this.isLoading = false
        })
      }
    },
    removeConfig(item) {
      let index = this.form.processConditionConfig.indexOf(item)
      if (index !== -1) {
        let _this = this
        this.$confirm({
          title: '',
          content: '确定删除该行?',
          onOk() {
            _this.form.processConditionConfig.splice(index, 1)
          },
          onCancel() {}
        })
      }
    },
    deleteNode() {
      let id = this.form.id
      if (!id) {
        this.$message.error('未有id')
        return
      }
      let _this = this
      this.$confirm({
        title: '删除节点流程条件配置',
        content: '确定删除节点流程条件配置?',
        onOk() {
          deleteAction('/act/processConditions/' + id).then(res => {
            if (res.success) {
              _this.$message.success('删除成功')
              _this.getConfig()
            } else {
              _this.$message.error(res.message)
            }
          })
        },
        onCancel() {}
      })
    },
    saveCopyVersion() {
      const postData = {
        actProcessId: this.info.id,
        targetDeploymentId: this.copyVersionId,
        deploymentId: this.copyVersion.deploymentId,
        duplicateAllConfig: this.duplicateAllAssignee
      }
      putAction('/act/processConditions/duplicate', postData).then(res => {
        if (res.success) {
          this.$message.success('拷贝成功')
          this.visibleVersion = false
        } else {
          this.$message.error(res.message)
        }
      })
    },
    cancelVisible() {
      this.visibleVersion = false
    },
    handleCopyVersion(row) {
      const postData = {
        actProcessId: this.info.id,
        deploymentId: row.deploymentId,
        pageSize: 500
      }
      getAction('/act/processConditions', postData).then(res => {
        if (res.result.rows.length) {
          this.visibleVersion = true
          this.copyVersion = row
        } else {
          this.$message.error('该流程无流程条件,无法拷贝')
        }
      })
    },
    handleCopyNode() {
      this.copyNode = this.selectDeploymentNode
      this.visibleNode = true
    },
    cancelVisibleNode() {
      this.visibleNode = false
    },
    saveCopyNode() {
      const postData = {
        actProcessId: this.info.id,
        targetDeploymentId: this.copyNode.deploymentId,
        deploymentId: this.copyNode.deploymentId,
        duplicateAllConfig: this.duplicateAllAssigneeNode,
        processNodeCodeMap: {}
      }
      postData.processNodeCodeMap[this.copyNode.processNodeCode] = this.copyNodeId
      putAction('/act/processConditions/duplicate', postData).then(res => {
        if (res.success) {
          this.$message.success('拷贝成功')
          this.visibleNode = false
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.ant-modal-header {
  //padding: 0 !important;
}
// 兼容1.6.2版本的antdv全屏
/deep/ .ant-modal {
  top: 0;
  padding: 0;
}
.content-wrapper {
  display: flex;
  height: 100%;
  padding: 20px;
  .content-left {
    width: 240px;
    height: 100%;
    border-right: 1px solid #999;
    padding-right: 20px;
    overflow: auto;
  }
  .content-main {
    width: calc(100% - 240px);
    height: 100%;
    padding: 20px;
    overflow: auto;
    .form-footer {
      text-align: center;
    }
  }
  .spin-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .version-list {
    color: #000;
    font-size: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 40px;
    flex-wrap: wrap;
    padding: 4px;
    border-radius: 8px;
    gap: 6px;
    margin-bottom: 4px;
    cursor: pointer;
    &.select {
      background: #f1f2f4;
    }
    /deep/.ant-tag {
      scale: 0.88;
      margin-right: 2px;
    }
    .version-tag {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 28px;
      height: 21px;
      margin-left: 4px;
      font-weight: 500;
      color: #24b35f;
      background-color: #edfcf0;
      border: 1px solid #8ad7a7;
      border-radius: 4px;
      > span {
        scale: 0.85;
        font-size: 12px;
      }
    }
  }
  .process-name {
    height: 60px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    color: #33383e;

    span {
      position: relative;
      display: inline-flex;
    }
    // > ::after {
    //   border-bottom: 1px solid #33383e;
    //   width: 100%;
    //   height: 1px;
    //   content: '';
    //   display: inline-block;
    //   position: absolute;
    //   bottom: -4px;
    // }
  }
  .deployment-node {
    display: inline-flex;
    color: #7f8792;
    margin-right: 14px;
    cursor: pointer;
    &.select {
      color: #000;
      border-bottom: 1px solid;
    }
  }
  .deployment-node-wrapper {
    display: flex;
    .deployment-node-title {
      display: inline-flex;
      padding-right: 20px;
    }
  }
  .assignee-configs-form {
    padding: 20px 0;
    .table-tool {
      padding-bottom: 10px;
      > button {
        margin-right: 10px;
      }
    }
    .assignee-configs-form-tip {
      padding-top: 20px;
    }
  }
  .assignee-configs-form-inner {
    border: 1px solid #f1f2f4;
    .table-header {
      // padding: 20px;
      > .ant-col {
        padding: 20px 0;
        border-right: 1px solid #f1f2f4;
        padding-left: 10px;
      }
    }
    .table-tr {
      border-top: 1px solid #f1f2f4;
      > .ant-col {
        border-right: 1px solid #f1f2f4;
        padding-left: 10px;
      }
      .form-delete {
        position: absolute;
        left: 8px;
        top: 7px;
        font-size: 20px;
        cursor: pointer;
      }
    }
    // padding: 20px 0;
  }
}
</style>
